package com.example.flasksale.listen;

import com.alibaba.fastjson.JSON;
import com.example.flasksale.entity.Order;
import com.example.flasksale.service.Consts;
import com.example.flasksale.service.OrderService;
import com.example.flasksale.service.OrderStatus;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(topic = Consts.TOPIC_ORDER_TIMEOUT,
        consumerGroup = "order_consumer02",
        consumeMode = ConsumeMode.CONCURRENTLY,
        messageModel = MessageModel.CLUSTERING,
        secretKey = "*")
public class OrderTimeoutListener implements RocketMQListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onMessage(Object object) {
        Order order = JSON.parseObject((String) object, Order.class);

        int status = orderService.findById(order.getId());

        if (status == OrderStatus.UNPAID.ordinal()) {

            // 取消订单
            orderService.cancel(order.getId());
            System.out.println("取消订单: " + order.getId());

            // 恢复库存
            Long increment = redisTemplate.opsForValue().increment(order.getProductId() + "");
            System.out.println("恢复库存: " + increment);
        }

    }
}
